package com.ailanyin.soft.config;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RuntimeUtil;
import com.ailanyin.soft.utils.MysqlUtil;
import com.ailanyin.soft.utils.NginxUtil;
import com.ailanyin.soft.utils.RedisUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * 安装配置
 *
 * @author ailanyin
 * @version 1.0
 * @since 2022-1-7 11:12:01
 */
public class InstallConfig {

    private static List<String> infos = new ArrayList<>();

    public static void menu() {
        boolean flag = true;

        while (flag) {
            System.out.println("请输入您的选择: ");
            System.out.println("1: 全量安装( Mysql + Nginx + Redis )");
            System.out.println("2: 手动安装 Mysql ");
            System.out.println("3: 手动安装 Nginx ");
            System.out.println("4: 手动安装 Redis ");
            System.out.println("5: 退出");
            Scanner sc = new Scanner(System.in);
            int choice = sc.nextInt();
            if (choice == 1) {
                startInstall();
                flag = false;
            }

            if (choice == 5) {
                flag = false;
            }
        }

    }

    private static void startInstall() {
        // 更新 yum
        yumUpdate();
        // 安装 Mysql 返回值 = newPassword
        infos.add("Mysql password: " + MysqlUtil.installMysql());
        // 安装 Nginx
        NginxUtil.installNginx();
        // 安装 Redis
        RedisUtil.installRedis();
        // 将信息保存到 /opt/ailanyin_install_info.txt 中
        saveInfoToFile();
    }

    private static void yumUpdate() {
        System.out.println("========== 正在更新 yum依赖,时间较长耐心等待... ==========");
        RuntimeUtil.getResult(RuntimeUtil.exec("yum update -y"));
        System.out.println("========== 完成更新 yum依赖 ==========");
    }

    private static void saveInfoToFile() {
        FileUtil.writeLines(infos, "/opt/ailanyin_install_info.txt", "UTF-8", false);
        System.out.println("安装任务已经完成! 相关信息已保存在 /opt/ailanyin_install_info.txt 中");
    }
}
